import {
  Button,
  Card,
  Cascader,
  Checkbox,
  Divider,
  Form,
  Icon,
  Input,
  InputNumber,
  Modal,
  message,
  Popconfirm,
  Radio,
  Select,
  Table,
  Tooltip,
  Upload,
} from 'antd';
import OtherSpec from '@/pages/Goods/components/OtherSpec';
import React, { Fragment, PureComponent, useEffect, useState, useRef } from 'react';
import PurchaseNewProductSku from '@/pages/Goods/components/PurchaseNewProductSku';
import { uploadUrl } from '@/config';
import BraftEditor from 'braft-editor';
import { bfUploadFn } from '@/utils/utils';
import GiveBackAddress from '@/pages/Goods/components/GiveBackAddress';
import Parameters from './components/Parameters';
import { LZFormItem } from '@/components/LZForm';
import { getToken } from '@/utils/localStorage';
import addressList from '@/assets/provinceAndCityAndArea.json';
import {isEqual} from "lodash";
import Prompt from "umi/prompt";
import router from "umi/router";
import NewProductSku from "@/pages/Goods/components/NewProductSku";
import RouterWillLeave from "@/components/RouterWillLeave";

const FormItem = Form.Item;
const { Option } = Select;
const RadioGroup = Radio.Group;

const largeFormItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 3 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
  },
};
const defaultDetail = {
  goodsDetail: { categoryId: '' },
  categories: [],
  compenRule: [],
  rentRule: [],
  backAddressList: [],
};

const goodsFormPurchase = Form.create()(props => {
  let {
    form,
    categories,
    goodsDetail = defaultDetail,
    changeSpecs,
    handleSubmit,
    onProductBuyout,
    cancel,
    addServiceTableData = [],
    giveBackList = [],
    deleteSpecs,
    changeSku,
    deleteSku,
  } = props;
  const { getFieldDecorator, getFieldValue } = form;
  const {
    categoryId,
    name,
    oldNewDegree,
    labels,
    shopAdditionals,
    isSupportStage,
    buyOutSupport,
    detail,
    images,
    province,
    city,
    freightType,
    addIds,
    productSkuses = [],
    specs = [],
    freightCost,
  } = goodsDetail;
  const [fileList, setFileList] = useState([]);
  const [parameters, setParameters] = useState([]);
  const [previewImage, setPreviewImage] = useState('');
  const [isBuyout, setIsBuyout] = useState(buyOutSupport);
  const [refs, setRefs] = useState([]);
  const liRefList = useRef([]);
  const [isSubmit, setIsSubmit] = useState(false);
  const [originPayload, setOriginPayload] = useState({});
  
  const [freightTypes, setfreightTypes] = useState(1);
  categories.map(v=>{
    v.children && v.children.map(child=>{
      if (child.children && !child.children.length) {
        delete child.children
      }
    })
  })
  let _specs = {},
    colorSpecs = {};
  specs.forEach(v => {
    if (v.opeSpecId === 1) {
      colorSpecs = v;
    } else {
      _specs = v;
    }
  });
  const items = Array.from({ length: 100 }, a => useRef(null));

  useEffect(() => {
    setIsBuyout(goodsDetail.isSupportStage);
  }, [goodsDetail.isSupportStage]);

  useEffect(() => {
    if (detail) {
      props.form.setFieldsValue({
        detail: BraftEditor.createEditorState(detail),
      });
    }
    if (images && images.length) {
      setFileList(
        images.map(v => ({ uid: v.src, url: v.src, src: v.src, isMain: v.isMain || null })),
      );
    }
    setParameters(goodsDetail.parameters);
  }, [detail, images, goodsDetail]);
  
  useEffect(() => {
    // setIsBuyout(goodsDetail.buyOutSupport);
    const values = form.getFieldsValue()
    const payload = getPayload(values)
    setOriginPayload(payload)
  }, [goodsDetail, detail, images, buyOutSupport, parameters]);

 

  const findInitCategory = id => {
    const cates = [];
    const findCategoryParentId = category => {
      let result;
      const find = e => {
        if (e.value === category) result = e;
        if (e.children) {
          for (let i = 0; i < e.children.length; i += 1) {
            find(e.children[i]);
          }
        }
      };
      categories.forEach(e => {
        find(e);
      });
      return result;
    };
    let element = findCategoryParentId(id);
    if (element) {
      cates.push(element);
    }
    while (element && element.parentId !== 0) {
      element = findCategoryParentId(element.parentId);
      cates.push(element);
    }
    if (cates) {
      return cates
        .map(e => {
          return e.value;
        })
        .reverse();
    }
    return [];
  };

  // 限制用户上传大小与格式
  const beforeUpload = file => {
    const isJPG =
      file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
    if (!isJPG) {
      message.error('图片格式不正确');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大于2MB');
    }
    return isJPG && isLt2M;
  };

  const checkMainImages = (_, value, callback) => {
    if (!value && fileList.length > 0) {
      callback('请上传主图');
      return;
    }
    callback();
  };
  const checkprice = (_, value, callback) => {
    if (!productSkuses.length) {
      callback('请填写租金');
      return;
    }
    callback();
  };

  const checkDetail = (_, value, callback) => {
    if (value.toHTML() === '<p></p>') {
      callback('请输入商品详情');
      return;
    }
    callback();
  };

  const validateAddress = (_rule, value, callback) => {
    if (!value || !value[0] || (!value[1] && province && city)) {
      callback('请选择发货地');
      return;
    }
    callback();
  };

  const changeBuyout = evt => {
    const value = evt.target.value;
    setIsBuyout(value);
  };

  const handleChangeSpecs = (value, opeSpecId) => {
    if (type === 'buyOutSupport') {
      onProductBuyout(value);
    }
    changeSpecs(value, opeSpecId);
  };

  const handleUploadImage = ({ file, fileList }) => {
    if (file.status === 'done') {
      const images = fileList.map((v, index) => {
        if (v.response) {
          const src = v.response.data;
          return { uid: index, src: src, url: src, isMain: v.isMain || null };
        }
        return v;
      });
      setFileList(images);
    }
    setFileList(fileList);
  };

  const handleChangeParam = val => {
    setParameters(val);
  };
  
  const getPayload = (fieldsValue) =>{
    const payload = fieldsValue;
    if (payload.detail) {
      payload.detail = payload.detail.toHTML();
    }
    payload.images = fileList.map((v, index) => {
      if (v.response) {
        const src = v.response.data;
        return { uid: index, src: src, url: src, isMain: v.isMain };
      }
      return v;
    });
    let addressObj = {};
    if (fieldsValue.address) {
      addressObj = {
        province: Number(fieldsValue.address[0]),
        city: Number(fieldsValue.address[1]),
      }
    }
    return {
      ...payload,
      ...addressObj,
      isBuyout: (fieldsValue.isBuyout || fieldsValue.isBuyout === 0) ? 0 : 1,
      parameters,
      isSupportStage: fieldsValue.isSupportStage,
    }
  }

  const handleSubmitForm = e => {
    e.preventDefault();
    form.validateFieldsAndScroll((err, fieldsValue) => {
      if (!err) {
        let hasError = false;
        items.map(item => {
          if (item.current) {
            item.current.validateFieldsAndScroll((err, fieldsValue) => {
              if (err) {
                hasError = true;
              }
            });
          }
        });
        if (hasError) {
          const errors = document.querySelector('.error-sale');
          if (errors) {
            message.error('存在' + errors.textContent + '的输入框');
            errors.scrollIntoView({ block: 'center' });
          }
        }
        if (!hasError) {
          setIsSubmit(true)
          const payload = getPayload(fieldsValue)
          handleSubmit(payload)
        }
      }
    });
  };

  let address = [];
  if (province && city) {
    address = [String(province), String(city)];
  }
  
  const handlePreview = ({ thumbUrl, url }) => {
    const imgUrl = thumbUrl ? thumbUrl : url
    setPreviewImage(imgUrl);
  };
  
  const handleCancel = () => {
    
    // cancel(isPrompt, isSubmit)
  }
  
  const renderRouterWillLeave=()=>{
    // const { isSubmit } = this.state
    const values = props.form.getFieldsValue()
    const payload = getPayload(values)
    let isPrompt = !isEqual(payload, originPayload)
    return (
      <RouterWillLeave isPrompt={isPrompt} isSubmit={isSubmit}  />
    )
  }
  
  return (
    <div className="goods-main">
      <Form {...largeFormItemLayout}>
        {
          renderRouterWillLeave()
        }
        <Card bordered={false}>
          <LZFormItem
            label="商品类目"
            field="categoryIds"
            requiredMessage="请选择商品类目"
            initialValue={findInitCategory(categoryId)}
            getFieldDecorator={getFieldDecorator}
          >
            <Cascader placeholder="请选择类目" options={categories || []} />
          </LZFormItem>
          <LZFormItem
            label="商品名称"
            field="name"
            requiredMessage="请输入商品名称"
            getFieldDecorator={getFieldDecorator}
            initialValue={name}
          >
            <Input placeholder="请输入商品名称" />
          </LZFormItem>
          <LZFormItem
            label="产品新旧"
            field="oldNewDegree"
            requiredMessage="请输入产品新旧"
            getFieldDecorator={getFieldDecorator}
            initialValue={oldNewDegree}
          >
            <Radio.Group>
              <Radio value={1}>全新</Radio>
              <Radio value={2}>99新</Radio>
              <Radio value={3}>95新</Radio>
              <Radio value={4}>9成新</Radio>
              <Radio value={5}>8成新</Radio>
              <Radio value={6}>7成新</Radio>
            </Radio.Group>
          </LZFormItem>
          <LZFormItem
            label="增值服务列表"
            field="shopAdditionals"
            getFieldDecorator={getFieldDecorator}
            initialValue={shopAdditionals || undefined}
          >
            <Select placeholder="请选择" mode="multiple">
              {addServiceTableData.map(value => {
                return (
                  <Select.Option value={value.id} label={value.name} key={value.id}>
                    {value.name}
                  </Select.Option>
                );
              })}
            </Select>
          </LZFormItem>
          <FormItem {...largeFormItemLayout} label="颜色分类">
            {getFieldDecorator('colorSpecs', {
              initialValue: colorSpecs || [],
            })(<OtherSpec opeSpecId={1} key="color" onChange={handleChangeSpecs} />)}
          </FormItem>
          <FormItem {...largeFormItemLayout} label="规格">
            {getFieldDecorator('specs', {
              initialValue: _specs || [],
            })(<OtherSpec opeSpecId={2} key="spec" onChange={handleChangeSpecs} />)}
          </FormItem>
          <FormItem {...largeFormItemLayout} required label="是否支持分期">
            {getFieldDecorator('isSupportStage', {
              initialValue: isSupportStage,
              rules: [{ required: true, message: '是否支持分期' }],
            })(
              <Radio.Group onChange={changeBuyout}>
                <Radio value={1}>支持分期</Radio>
                <Radio value={0}>不支持分期</Radio>
              </Radio.Group>,
            )}
          </FormItem>
          <FormItem label="购买金额" required>
            {getFieldDecorator('price', {
              rules: [{ validator: checkprice }],
            })(
              <div>
                {productSkuses.map((p, index) => {
                  return (
                    <PurchaseNewProductSku
                      getFieldDecorator={getFieldDecorator}
                      oldNewDegree={oldNewDegree}
                      ref={items[index]}
                      key={p.skuId}
                      isBuyout={isBuyout}
                      changeSku={changeSku}
                      deleteSpecs={deleteSpecs}
                      deleteSku={deleteSku}
                      specs={_specs}
                      colorSpecs={colorSpecs}
                      index={index}
                      productSkuses={p}
                    />
                  );
                })}
              </div>,
            )}
          </FormItem>
          <FormItem {...largeFormItemLayout} required label="商品图片">
            {getFieldDecorator('images', {
              initialValue: goodsDetail.images,
              rules: [{ validator: checkMainImages }],
            })(
              <div className="upload-desc">
                <Upload
                  accept="image/*"
                  action={uploadUrl}
                  listType="picture-card"
                  headers={{
                    token: getToken(),
                  }}
                  fileList={fileList}
                  onPreview={handlePreview} //预览
                  beforeUpload={beforeUpload}
                  onChange={handleUploadImage}
                >
                  <div>
                    <Icon type="upload" />
                    <div className="ant-upload-text">上传照片</div>
                  </div>
                </Upload>
                <div className="size-desc w294">
                  <span>● 尺寸为700x700px及以上正方形</span>
                  <br />
                  <span>● 不能出现商家logo、水印、电话、微信等联系方式</span>
                  <br />
                  <span>● 其中第一张图要求为纯白色底图</span>
                </div>
              </div>,
            )}
          </FormItem>
          <FormItem {...largeFormItemLayout} required label="商品详情">
            {getFieldDecorator('detail', {
              initialValue: BraftEditor.createEditorState(goodsDetail.detail),
              rules: [{ validator: checkDetail }],
            })(
              <BraftEditor
                style={{ border: '1px solid #d1d1d1', borderRadius: 5, backgroundColor: '#fff' }}
                contentStyle={{ height: 500, boxShadow: 'inset 0 1px 3px rgba(0,0,0,.1)' }}
                excludeControls={['emoji', 'clear', 'blockquote', 'code']}
                media={{ uploadFn: bfUploadFn }}
              />,
            )}
          </FormItem>
          <FormItem
            label="商品参数"
            field="labels"
            getFieldDecorator={getFieldDecorator}
            initialValue={labels || undefined}
          >
            <div>
              <Parameters parameters={parameters} onChange={handleChangeParam} />
            </div>
          </FormItem>
          <Form.Item label="发货地" required>
            {getFieldDecorator('address', {
              rules: [
                {
                  validator: validateAddress,
                },
              ],
              initialValue: address,
            })(<Cascader options={addressList} placeholder="请选择" />)}
          </Form.Item>
          <LZFormItem
            label="快递"
            field="freightType"
            requiredMessage="请选择快递方式"
            getFieldDecorator={getFieldDecorator}
            initialValue={freightType}
          >
            <Radio.Group>
              <Radio value={'FREE'}>包邮</Radio>
              <Radio value={'PAY'}>到付</Radio>
              <Radio value={'SELF'}>自提</Radio>
              <Radio value={'CUSTOMIZE'}>运费</Radio>
            </Radio.Group>
          </LZFormItem>
          {getFieldValue('freightType') === 'CUSTOMIZE' ? (
            <FormItem {...largeFormItemLayout} required label="运费">
              {getFieldDecorator('freightCost', {
                initialValue: freightCost,
                rules: [{ type: 'number', required: true, message: '请选择是否上架' }],
              })(<InputNumber style={{ width: 100 }} />)}
            </FormItem>
          ) : null}
      
          <FormItem {...largeFormItemLayout} required label="是否上架">
            {getFieldDecorator('type', {
              initialValue: goodsDetail.type,
              rules: [{ type: 'number', required: true, message: '请选择是否上架' }],
            })(
              <RadioGroup>
                <Radio value={1}>上架</Radio>
                <Radio value={2}>放入仓库</Radio>
              </RadioGroup>,
            )}
          </FormItem>
        </Card>
    
        <FormItem {...largeFormItemLayout} required label="退货地址">
          {getFieldDecorator('addIds', {
            initialValue: addIds,
            rules: [{ type: 'array', required: true, message: '请选择退货地址' }],
          })(<GiveBackAddress addressList={giveBackList} />)}
          {/*<Button icon="reload" style={{ margin: 'auto 10px' }} onClick={setInitList} />*/}
          {/*<Button onClick={() => gotoRole('backAddress')}>设置归还地址</Button>*/}
        </FormItem>
    
        <Form.Item wrapperCol={{ offset: 3 }}>
          <Button onClick={cancel} className="w70">
            取消
          </Button>
          <Button type="primary" onClick={handleSubmitForm} className="w-112">
            确定
          </Button>
        </Form.Item>
    
        <Modal
          visible={!!previewImage}
          footer={null}
          onCancel={() => setPreviewImage('')}
          width={600}
        >
          <img src={previewImage} alt="" style={{ width: '100%', paddingTop: 15 }} />
        </Modal>
      </Form>

    </div>
  );
});

export default goodsFormPurchase;
